﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Perovich.GameObjects.Interfaces;
using Perovich.GameObjects.Attributes;
using System.CodeDom;
using Perovich.GameObjects.Tools.Util;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Perovich.GameObjects.Components
{
    [AutomaticInterface(typeof(ICanHoldComponents))]
    [AutomaticProperty("Components", "EntityContainer.Components", IsReadOnly = true)]
    [AutomaticProperty(typeof(EntityContainer), "GenerateProperty")]
    [AutomaticImport("Perovich.GameObjects", false)]
    [AutomaticImport("Perovich.GameObjects.Interfaces", false)]
    public sealed class EntityContainer : DrawableEntityComponent
    {
#if WINDOWS
        public static AutoProperty GenerateProperty(CodeExpression me)
        {
            var target = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "GameServices");
            var prop = new AutoProperty("ICanSupportComponents.Services", "IServiceProvider", target, 0);
            prop.IsReadOnly = true;
            return prop;
        }
#endif

        private ComponentCollection _components = new ComponentCollection();

        public ComponentCollection Components
        {
            get { return _components; }
        }

        private IGraphicsDeviceService GraphicsDeviceService;


        public override void Initialize()
        {
            Components.Initialize();
            base.Initialize();
        }


        public override void LoadContent()
        {
            GraphicsDeviceService = (IGraphicsDeviceService)Owner.Parent.Services.GetService(typeof(IGraphicsDeviceService));
            base.LoadContent();
        }
        public override void Update(GameTime gameTime)
        {
            if (Enabled)
            {
                base.Update(gameTime);
                Components.Update(gameTime);
                Perovich.GameObjects.ComponentsExtensions.CheckColisions(Components);
            }
        }

        public override void DrawOnTargets(GameTime gameTime)
        {
            if (Visible)
            {
                Components.DrawOnTargets(gameTime);
                base.DrawOnTargets(gameTime);
            }
        }

        public override void Draw(GameTime gameTime)
        {
            if (Visible)
            {
                Components.Draw(gameTime, GraphicsDeviceService.GraphicsDevice, Owner.SBatches);
                base.Draw(gameTime);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Components.Dispose();
            }
            base.Dispose(disposing);
        }


    }
}